const { md5, encrypt, decrypt } = require("../utils.js");

const SqliteDB = require("./db.js").SqliteDB;
const sqliteDB = new SqliteDB();

const createTableSqls = [
  'CREATE TABLE IF NOT EXISTS "accounts" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"brandname" TEXT,"nickname" TEXT,"userid" TEXT,"cookie" TEXT,"enable" INTEGER,"uid" INTEGER);',
  'CREATE TABLE IF NOT EXISTS "user" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"username" TEXT,"password" TEXT DEFAULT e10adc3949ba59abbe56e057f20f883e,"main_account_id" INTEGER,"token" TEXT);',
];

createTableSqls.forEach((sql) => {
  sqliteDB.createTable(sql);
});

exports.sqliteDB = sqliteDB;

exports.checkToken = (token) => {
  const querySql = `select * from user where token = "${token}"`;
  return sqliteDB.queryData(querySql);
};

exports.login = async (username, password) => {
  const querySql = `select * from user where username = "${username}"`;
  const user = (await sqliteDB.queryData(querySql))[0];
  if (!user) {
    return false;
  }

  if (md5(password) != user.password) {
    return false;
  }
  user.token = encrypt({
    id: user.id,
    username: user.username,
    password: user.password,
  });
  const updateSql = `update user set token = "${user.token}" where id = ${user.id}`;
  sqliteDB.executeSql(updateSql);
  delete user.password;
  return user;
};

exports.addAccount = async (uid, data) => {};

exports.saveAccount = async (uid, userid, data) => {
  const table = "accounts";
  const where = `uid = '${uid}' and userid = '${userid}'`;
  const querySql = `select * from ${table} where ${where}`;
  const account = (await sqliteDB.queryData(querySql))[0];
  if (account) {
    let arr = [];
    for (const key in account) {
      if (Object.hasOwnProperty.call(data, key)) {
        arr.push(`${key} = '${data[key]}'`);
      }
    }
    // update
    const updateSql = `update ${table} set ${arr.join(",")} where ${where}`;
    sqliteDB.executeSql(updateSql);
  } else {
    const fields = await sqliteDB.queryData("pragma table_info ('accounts')");
    let insertData = {};
    fields.forEach((el) => {
      if (el.pk) {
        return;
      }
      insertData[el.name] = "";
      if (Object.hasOwnProperty.call(data, el.name)) {
        insertData[el.name] = data[el.name];
      }
    });
    insertData.uid = uid;
    insertData.userid = userid;
    const keys = Object.keys(insertData);
    const vals = new Array(keys.length).fill("?").join(",");
    const insertSql = `insert into ${table}(${keys.join(",")}) values(${vals})`;
    sqliteDB.insertData(insertSql, [Object.values(insertData)]);
  }
  return (await sqliteDB.queryData(querySql))[0];
};

exports.removeAccount = (id) => {
  sqliteDB.executeSql(`DELETE FROM accounts WHERE id=${id}`);
};
